package com.liang.manage.auth.facade.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.liang.nansheng.common.constant.TimeoutConstants;

import java.util.Date;

/**
 * JWT的构成（header.playload.signature）
 *
 * @author 马亮
 * @date 2021/4/25 15:21
 */
public class JwtUtil {
    /**
     * JWT-playLoad (载荷就是存放有效信息的地方)
     */
    public static final String ACCOUNT = "playLoad";

    /**
     * JWT-currentTimeMillis
     */
    public final static String CURRENT_TIME_MILLIS = "currentTimeMillis";
    /**
     * 失效时间 单位毫秒
     */
    public static final long REFRESH_TOKEN_EXPIRE_TIME = TimeoutConstants.NS_SSO_TIMEOUT * 1000L;
    /**
     * JWT-secret_key
     */
    public static final String SECRET_KEY = "storewebkey";

    /**
     * 校验token是否正确
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            String secret = getClaim(token) + SECRET_KEY;
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获得Token中的信息无需secret解密也能获得
     *
     * @param token
     * @return
     */
    public static Long getClaim(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(ACCOUNT).asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名
     *
     * @param account
     * @param currentTimeMillis
     * @return
     */
    public static String sign(Long account, String currentTimeMillis) {
        // 帐号加JWT私钥加密
        String secret = account + SECRET_KEY;
        // 此处过期时间，单位：毫秒
        Date date = new Date(System.currentTimeMillis() + REFRESH_TOKEN_EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);

        return JWT.create()
                .withClaim(ACCOUNT, account)
                .withClaim(CURRENT_TIME_MILLIS, currentTimeMillis)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static void main(String[] args) {
        String token = JwtUtil.sign(78878L, String.valueOf(System.currentTimeMillis()));
        System.out.println(token);
        System.out.println(JwtUtil.verify(token));
        System.out.println(JwtUtil.getClaim(token));
    }

}
